<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/20
 * Time: 15:31
 */
namespace app\home\controller;
use app\common\model\AmountLog;
use app\common\model\CommunityJoin;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\UserCommission;
use app\Request;
class Community
{
    public function addCommunity(Request $request){
        $param  = $request->param();
        $data = [
            'name' => $param['name'],
            'desc' => $param['desc'],
            'allow_join_number' => $param['allow_join_number'],
            'img' => $param['img'],
            'uid' => $request->userInfo['id'],
            'price' =>  $param['price'],
            'create_time' => time(),
            'head_img' => $param['head_img'],
        ];
        if ($request->userInfo['level_id'] >1){
            $community_number = Config::getConfigValue('level_community_number');
        }else{
            $community_number = Config::getConfigValue('community_number');
        }
        $communityModel = new \app\common\model\Community();
        if ($community_number  >= 0  ){
            $todayDaziCount = $communityModel->where('create_time'  ,strtotime(date('Y-m-d 00:00:00')))
                ->where('uid','=', $request->userInfo['id'])
                /*  ->where('status','in',[1,2,5])*/
                ->count();
            if ($community_number <= $todayDaziCount ){
                return error('发布数量已达上限');
            }
        }
        $isAuditing = Config::getConfigValue('community_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        if ($isAuditing != 1){
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '社群'],
                'thing2' => ['value' => $data['name']],
                'phrase3' => ['value' =>'通过'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] = [$request->userInfo['id']];
            $xcxMessage[0]['title'] ='release';
            $messageModel->sendMessage(3,$xcxMessage);
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'社群'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$data['name']],
                'thing2' => ['value' => '通过'],
            ];
            $gzhMessage[0]['uid'] =$request->userInfo['id'];
            $gzhMessage[0]['title'] ='release';
            $messageModel->sendMessage(1,$gzhMessage);
        }
        $communityModel->insert($data);
        return success('发布成功');
    }

    public function communityList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit + $start;
        }
        $where[]  =['status','<>',4];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['name','like','%'.$param['name'].'%'];
        }

        if (isset($param['is_oneself']) && !empty($param['is_oneself'])) {
            $where[] = ['uid','=',$request->userInfo['id']];
        }else{
            $where[] = ['status','=',2];
        }

        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['uid','=',$param['uid']];
            $where[] = ['status','=',2];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['status','=',$param['status']];
        }
        $communityModel = new \app\common\model\Community();
        $list = $communityModel->where($where)->limit($start,$limit) ->order('sort','desc')->select()->toArray();
        $communityJoinModel = new CommunityJoin();
        foreach ($list as $key => $value){
            if (isset($param['oneself_uid']) && !empty($param['oneself_uid'])) {
                $communityJoinInfo = $communityJoinModel->where(['community_id' => $value['id'], 'uid' => $param['oneself_uid']])->find();
                if ($communityJoinInfo){
                    $list[$key]['is_join'] = 1;
                }else{
                    $list[$key]['is_join'] = 0;
                }
            }else{
                $list[$key]['is_join'] = 0;
            }

        }
        $count = $communityModel->where($where)->limit($start,$limit)->count();
        return success('社群列表',['list' => $list,'count' => $count]);
    }

    public function joinCommunity(Request $request){
        $param = $request->param();
        $communityModel = new \app\common\model\Community();
        $communityInfo = $communityModel->where(['id' =>$param['community_id'] ])->find();
        $communityJoinModel = new CommunityJoin();
        if (empty($communityInfo)){
            return error('社群有误');
        }
        $communityJoinInfo =  $communityJoinModel->where([ 'community_id' => $param['community_id'],'uid' => $request->userInfo['id'] ])->find();
        if ($communityJoinInfo){
            return error('已加入');
        }
        $community_level_discount = 0;
        $discountAmount  = $communityInfo['price'] ;
        if ($request->userInfo['level_id']  > 1){
            $community_level_discount  = Config::getConfigValue('community_level_discount');
            if ($community_level_discount >0){
                $discountAmount = bcdiv(bcmul($communityInfo['price'],$community_level_discount,2),100,2);
            }
        }
        if ($request->userInfo['balance']<$discountAmount ){
            return error('用户余额不足',[],'1001');
        }
        $data = [
            'community_id' => $param['community_id'],
            'price' =>  $discountAmount,
            'original_price'=> $communityInfo['price'] ,
            'discount'  => $community_level_discount,
            'create_time' => time(),
            'uid' => $request->userInfo['id'],
        ];
        $communityJoinModel->insert($data);
        $userModel = new \app\common\model\User();
        if ($communityInfo['price'] > 0 ){
            $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$discountAmount)->update();
         //   $userCommissionModel = new UserCommission();
           // $userCommissionModel->addUserCommission($request->userInfo['id'],$discountAmount,3,$communityInfo['id']);
            $communityModel->where(['id' => $param['community_id']])->inc('join_number')->update();
            $recharge_ratio  = Config::getConfigValue('recharge_ratio');
            $amountModel = new AmountLog();
            $amountData  = [
                'uid' =>$request->userInfo['id'],
                'amount' => $discountAmount,
                'amount_type' => 1,
                'amount_direction' => 2,
                'create_time' => time(),
                'correlation_id' => $communityInfo['id'],
                'operation_source' => 12,
                'handling_fees_amount' => bcdiv($discountAmount,$recharge_ratio,2),
                'handling_fees' => $discountAmount,
                'original_price' => $communityInfo['price']
            ];
            $amountModel->insert($amountData);
        }
       /* $messageModel = new MessageTemplate();
        $xcxMessage[0]['data'] = [
            'thing1' => ['value' => '社群'],
            'thing2' => ['value' => $communityInfo['name']],
            'phrase3' => ['value' =>$request->userInfo['nickname'].'加入'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] = [$request->userInfo['id']];
        $xcxMessage[0]['title'] ='release';
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'社群'],
            'thing28' => ['value' => $request->userInfo['nickname'] ],
            'thing9' => ['value' =>$communityInfo['name']],
            'thing2' => ['value' => '加入'],
        ];
        $gzhMessage[0]['uid'] =$request->userInfo['id'];
        $gzhMessage[0]['title'] ='release';
        if ($communityInfo['price'] > 0){
            $xcxMessage[1]['data'] =  [
                'amount2' => ['value' => $discountAmount],
                'thing8' => ['value' => '加入社群'],
                'thing5' => ['value' => $communityInfo['name']],
                'time4' =>  ['value' => date('Y-m-d H:i')],
            ];
            $xcxMessage[1]['uid'] = $request->userInfo['id'];
            $xcxMessage[1]['title'] ='consumption';
            $gzhMessage[1]['data'] = [
                'thing2' => ['value' =>'加入社群'],
                'thing37' => ['value' => $communityInfo['name'] ],
                'amount3' => ['value' =>$discountAmount],
                'time3' => ['value' => date('Y-m-d H:i')],
            ];
            $gzhMessage[1]['uid'] =$request->userInfo['id'];
            $gzhMessage[1]['title'] ='consumption';
        }
        $messageModel->sendMessage(1,$gzhMessage);
        $messageModel->sendMessage(3,$xcxMessage);
        $messageModel-> sendAliMessage($communityInfo['uid'], 'release', ['name' =>'社区'. $communityInfo['name'],'desc'=>'新用户加入']);*/

        return success('操作成功');
    }

    public function communityInfo(Request $request){
        $param = $request->param();
        $communityModel = new \app\common\model\Community();
        $communityInfo = $communityModel->where(['id' =>$param['community_id'] ])->find();
        $communityJoinModel = new CommunityJoin();
        $communityJoinInfo = $communityJoinModel->where(['community_id' =>$param['community_id'],'uid'=>$request->userInfo['id'] ])->find();
       if ($communityJoinInfo){
           $communityInfo['is_join'] = 1;
       }else{
           $communityInfo['is_join'] = 0;
       }
        return success('社群列表',$communityInfo);
    }

    public function editCommunity(Request $request){
        $param  = $request->param();
        $data = [
            'name' => $param['name'],
            'desc' => $param['desc'],
            'allow_join_number' => $param['allow_join_number'],
            'img' => $param['img'],
            'uid' => $request->userInfo['id'],
            'price' =>  $param['price'],
            'create_time' => time(),
            'head_img' => $param['head_img'],
        ];
        $levelModel = new Level();
        $communityModel = new \app\common\model\Community();
        $levelInfo  = $levelModel->where(['id' => $request->userInfo['level_id']])->find();
      /*  if ($levelInfo['community_number']  == 0 ){
            return error('请升级会员',[],'1001');
        }*/
    /*
        if ($levelInfo['community_number']  >0  ){
            $todayDaziCount = $communityModel->where('create_time'  ,strtotime(date('Y-m-d 00:00:00')))
                ->where('uid','=', $request->userInfo['id'])

                ->count();
            if ($levelInfo['community_number'] <= $todayDaziCount ){
                return error('今日发布数量已达上限');
            }
        }*/
        $isAuditing = Config::getConfigValue('community_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        $communityModel->where(['id' => $param['id']])->update($data);
        return success('发布成功');
    }

    public function updateCommunityStatus(Request $request){
        $param = $request->param();
        $CommunityModel = new \app\common\model\Community();
        $data['status']  =  $param['status'];
        if (isset($param['remark']) && !empty($param['remark'])){
            $data['remark'] = $param['remark'];
        }
        $CommunityModel->where(['id' => $param['id']])->update($data);
        return  success('操作成功');
    }

    public function myJoinCommunity(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit + $start;
        }
        $where = [];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['name','like','%'.$param['name'].'%'];
        }
        $CommunityJoinModel = new \app\common\model\CommunityJoin();
        $list = $CommunityJoinModel->alias('cj')
            ->leftJoin('community c', 'cj.community_id = c.id')
            ->leftJoin('user u', 'c.uid = u.id')
            ->leftJoin('user uj', 'cj.uid = uj.id')
            ->where($where)
            ->where(['cj.uid' => $request->userInfo['id']])
            ->field('cj.*,c.name,c.head_img, c.desc,u.nickname,c.join_number,c.allow_join_number,u.avatar,uj.nickname as join_nickname,uj.avatar as join_avatar ')

            ->limit($start,$limit)->select()->toArray();
        $count = $CommunityJoinModel->alias('c')
            ->leftJoin('user u', 'c.uid = u.id')
            ->where($where)
            ->leftJoin('community_join cj', 'cj.community_id = c.id')
            ->leftJoin('user uj', 'cj.uid = uj.id')
            ->where(['cj.uid' => $request->userInfo['id']])
            ->field('c.*,u.nickname,u.avatar,uj.nickname as join_nickname,uj.avatar as ')

            ->count();
        return success('加入社群数据',['list' => $list,'count' => $count]);
    }

    public function  communityUser(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit + $start;
        }
        $where[]   =['community_id' ,'=', $param['id'] ] ;
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[]   = ['nickname','like','%'.$param['nickname'].'%'] ;
        }
        $communityJoinModel = new \app\common\model\CommunityJoin();
        $list = $communityJoinModel->alias('cj')
            ->leftJoin('user u', 'cj.uid = u.id')
            ->field('cj.*,u.nickname,u.avatar ')
            ->where($where)->limit($start,$limit) ->order('sort','desc')->select()->toArray();
        $count = $communityJoinModel->alias('cj')
            ->leftJoin('user u', 'cj.uid = u.id')->where($where)->limit($start,$limit)->count();
        return success('社群用户',['list' => $list,'count' => $count]);
    }

}